<template>
  <div class="ss">
    <el-row>
      <el-col :sm="{ span: 8, offset: 8 }" :xs="{ span: 24, offset: 0 }">
        <div class="grid-content bg-purple-dark">
          <div>
            <div class="zt">
              <span class="title" style="font-weight: bold">注册账户</span>
            </div>
            <!--注册账号 #start -->
            <el-form
              :model="ruleForm"
              status-icon
              :rules="rules"
              ref="ruleForm"
              label-width="100px"
              class="demo-ruleForm"
            >
              <el-form-item label="账号：" prop="userAccount">
                <el-input
                  placeholder="请填写 3-10位 字母/数字 组合"
                  class="ss1"
                  type="text"
                  v-model="ruleForm.userAccount"
                  autocomplete="off"
                ></el-input>
              </el-form-item>

              <el-form-item label="用户名：" prop="userName">
                <el-input
                  placeholder="请填写 2-10位 字母/数字/汉字/下划线 组合"
                  class="ss1"
                  type="text"
                  v-model="ruleForm.userName"
                  autocomplete="off"
                ></el-input>
              </el-form-item>

              <el-form-item label="邮箱：" prop="userEmail">
                <div style="display: flex">
                <el-input
                  placeholder="请输入邮箱"
                  class="ss1"
                  type="text"
                  v-model="ruleForm.userEmail"
                  autocomplete="off"
                ></el-input>
                <el-button type="primary"
                           @click="sendCode"
                           :disabled="isSending"
                           style="margin-left: 5px">
                  {{ isSending ? `${countdown}s后重新发送` : '发送验证码' }}
                </el-button>
                </div>
              </el-form-item>

              <el-form-item label="验证码：" prop="code">
                <el-input
                  placeholder="请输入验证码"
                  class="ss1"
                  type="text"
                  v-model="ruleForm.code"
                  autocomplete="off"
                ></el-input>
              </el-form-item>

              <el-form-item label="密码：" prop="password">
                <el-input
                  placeholder="密码"
                  class="ss1"
                  type="password"
                  show-password
                  v-model="ruleForm.password"
                  autocomplete="off"
                ></el-input>
              </el-form-item>

              <el-form-item label="确认密码：" prop="checkPass">
                <el-input
                  placeholder="再次输入密码"
                  class="ss1"
                  type="password"
                  show-password
                  v-model="ruleForm.checkPass"
                  autocomplete="off"
                ></el-input>
              </el-form-item>

              <router-link
                :to="{ path: 'userlogin' }"
                class="router-link-active"
              >
                <el-form-item>
                  <el-link type="primary">已有账号？点击登录</el-link>
                </el-form-item>
              </router-link>
              <el-form-item style="margin-right: -50px">
                <el-button
                  type="primary"
                  @click="submitForm('ruleForm')"
                  style="margin-right: 10px"
                >提交</el-button
                >
                <el-button type="info" @click="resetForm('ruleForm')">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div></el-col
      >
    </el-row>

    <!--注册 #end -->
  </div>
</template>
<script>
import apiService from "@/api/service";
import apiTourist from "@/api/tourist";
import apiUserInfo from "@/api/userInfo";

export default {
  data() {
    const validateAccount = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入账号"));
      } else {
        this.loginVo.userAccount = value;
        apiTourist.isExist(this.loginVo).then((response) => {
          if (response.data === true) {
            callback(new Error("账号已经存在"));
          } else {
            callback();
          }
        }).catch(() => {
          callback(new Error("验证失败，请重试"));
        });
      }
    };

    const validateName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else {
        callback();
      }
    };

    const validateEmail = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入邮箱号"));
      } else {
        this.loginVo.userEmail = value;
        apiTourist.isExist(this.loginVo).then((response) => {
          if (response.data === true) {
            callback(new Error("邮箱已经存在"));
          } else {
            callback();
          }
        }).catch(() => {
          callback(new Error("验证失败，请重试"));
        });
      }
    };

    const validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };

    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };

    return {
      ruleForm: {
        password: "",
        checkPass: "",
        userEmail: "",
        userName: "",
        userAccount: "",
        code: "",
      },
      rules: {
        userAccount: [{ required: true, validator: validateAccount, trigger: "blur" }],
        userName: [{ required: true, validator: validateName, trigger: "blur" }],
        userEmail: [
          { required: true, validator: validateEmail, trigger: "blur" },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        password: [{ required: true, validator: validatePass, trigger: "blur" }],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
        checkPass: [{ required: true, validator: validatePass2, trigger: "blur" }],
      },
      loginVo: {},
      imageUrl: "",
      isSending: false, // 添加这个属性来控制按钮的可点击状态
      countdown: 600
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //参数正确时：
          this.loginVo.userAccount = this.ruleForm.userAccount;
          this.loginVo.userName = this.ruleForm.userName;
          this.loginVo.password = this.ruleForm.password;
          this.loginVo.code = this.ruleForm.code;
          this.loginVo.userName = this.ruleForm.userName;

          apiUserInfo.register(this.loginVo)
            .then(() => {
              this.$message.success("注册成功，请登录！");
              this.$router.push({ path: "/userlogin" });
            })
            .catch(error => {
              this.$message.error("注册失败");
            });
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //发送验证码
    sendCode() {
      if (this.isSending) return;

      apiService
        .sendMailCode(this.ruleForm.userEmail)
        .then((response) => {
          this.$message.success(response.data);
          this.isSending = true;
          let timer = setInterval(() => {
            this.countdown--;
            if (this.countdown <= 0) {
              clearInterval(timer);
              this.isSending = false;
              this.countdown = 600; // 重置计数器
            }
          }, 1000);
        })
        .catch((response) => {
          this.$message.error("请填写邮箱");
        });
    },
  },
};
</script>
<style>
.zt {
  width: 100%;
  text-align: center;
  padding: 20px;
}
.ss {
  margin: 0 auto;
  height: 100%;
}

.router-link-active {
  text-decoration: none;
}
/* 头像 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

</style>
